using System.Collections.Generic;
using System.Globalization;
using UnityEngine;

/****************************************************
// 功能：屏幕点击特效
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/2/21 17:1:40
*****************************************************/

public class ScreenTapFx : MonoBehaviour
{
    // 屏幕特效资源
    public GameObject game;
    // 屏幕特效停留时长，超过后进行缓存
    public float fxTime = 1.0f;
    // 特效的容器对象
    public RectTransform rectTransform;
    public Camera renderCamera;
    private readonly Queue<GameObject> pool = new Queue<GameObject>();
    private readonly List<GameObject> listGame = new List<GameObject>();


    private void Awake()
    {
        if (game == null)
        {
            this.enabled = false;
        }
        else
        {
            game.SetActive(false);
        }
    }

    void Start()
    {
        renderCamera = Camera.main;
    }

    
    void Update()
    {
        for (int i = listGame.Count - 1; i >= 0; --i)
        {
            GameObject fx = listGame[i];
            float time = float.Parse(fx.name);
            
            // 超过fxTime，则回收
            if (Time.time - time > fxTime)
            {
                RecycleFx(fx);
                listGame.RemoveAt(i);
            }
        }
        
        // 根据平台检测输入
        if (Application.isMobilePlatform)
        {
            for (int i = 0; i < Input.touchCount; ++i)
            {
                Touch touch = Input.GetTouch(i);
                if (touch.phase == TouchPhase.Began)
                {
                    PlayFx(touch.position);
                }
            }
        }
        else
        {
            // PC端，处理鼠标左侧点击事件
            if (Input.GetMouseButtonDown(0))
            {
                PlayFx(Input.mousePosition);
            }
        }
    }

    private void PlayFx(Vector2 tapPos)
    {
        GameObject fx = CreateFx();
        
        // 将当前时间作为对象名
        fx.name = Time.time.ToString(CultureInfo.InvariantCulture);
        // 添加到列表里面
        listGame.Add(fx);
        // 获取坐标
        RectTransform fxRectTransform = fx.GetComponent<RectTransform>();
        fxRectTransform.SetParent(rectTransform);
        
        // 将屏幕坐标转到本地坐标
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, tapPos, renderCamera, out var localPostion);
        // 设置锚点
        fxRectTransform.anchoredPosition3D = localPostion;
        fx.SetActive(true);
    }
    
    
    private GameObject CreateFx()
    {
        GameObject newFx = null;
        newFx = pool.Count > 0 ? pool.Dequeue() : Instantiate(game);
        return newFx;
    }
    
    private void RecycleFx(GameObject fx)
    {
        fx.SetActive(false);
        pool.Enqueue(fx);
    }
}
